package com.wuxuan.algorithm_homework.sortTest;

import java.util.Arrays;

/**
 * 归并排序
 */
public class mergeSort {
    private final int N = 100000;
    int[] tmp = new int[N];

    public int[] mergeSort(int[] q) {
        if (q == null || q.length == 0) {
            return q;
        }

        int[] helper = new int[q.length];
        mergeSort(q, 0, q.length - 1);
        return q;
    }


    private void mergeSort(int[] q, int l, int r) {
        if (l >= r) {
            return;
        }

        int mid = l + (r - l) / 2;

        //将左边和右边各自排序好
        mergeSort(q, l, mid);
        mergeSort(q, mid + 1, r);

        //合并
        merge(q, l, mid, r);
    }

    private void merge(int[] q, int l, int mid, int r) {
        //整体排序好
        int k = l;
        int i = l;
        int j = mid + 1;

        while (i <= mid && j <= r) {
            if (q[i] <= q[j]) {
                tmp[k++] = q[i++];
            } else {
                tmp[k++] = q[j++];
            }
        }

        while (i <= mid) {
            tmp[k++] = q[i++];
        }
        while (j <= r) {
            tmp[k++] = q[j++];
        }

        for (i = l; i <= r; i++) {
            //这里只是复制了值！！！
            q[i] = tmp[i];
        }

    }

    public static void main(String[] args) {
        mergeSort ms = new mergeSort();

        int[] q = {5, 3, 4, 1, 9, 8, 7, 6};

        System.out.println(Arrays.toString(q));

        int[] result = ms.mergeSort(q);

        System.out.println(Arrays.toString(result));

    }
}
